<?php

/**
 * Author: turbo
 * 2018-08-24 16:30:23
 */

namespace Common\Util;

/**
 * 物流信息查询，基于百度接口查询
 */
class Express
{
    const API = 'https://sp0.baidu.com/9_Q4sjW91Qh3otqbppnN2DJv/pae/channel/data/asyncqury?cb=&appid=4001&com=&vcode=&token=&_=1532192395053';

    const HEADER = [
    	"Cookie:BAIDUID=916F3E2F4B28994074476B12FC255A29:FG=1; BIDUPSID=916F3E2F4B28994074476B12FC255A29; PSTM=1481444312; BDUSS=JxUWNXfldyTEVSd09uU0lFME5GRkluZFJkMmJUTGlyMnFTcDlOVElxa2YxQmRhSVFBQUFBJCQAAAAAAAAAAAEAAAC0em0KNjY0MTIwNDU5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB9H8FkfR~BZMW; __cfduid=dff2158a8dba56bc5b077509eae4b9f971509334072; BAEID=A6DB3A3D69FB89A991E6C181DFDA0F1D; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=1440_21122_18559_20928; BDSFRCVID=a1IsJeC62Gvv4pR7_BKqEXvch2qkLfjTH6aIGEsyHvwFSCz8SXJGEG0PjM8g0KubvfegogKK0mOTHvjP; H_BDCLCKID_SF=tR4toKDKtI83fP36qR7E-tCyMhoK5toyHD7yWCvmt-55OR5Jj6KB3UDYj-PfyMrmJ2TvLJOSWbb5VIK63MA--fc0KajeWU3l3bTN-lcp3x-Vsq0x0MOte-bQyp_LWjkObCOMahkMal7xO-QF05CKjjbLDauOq6n0bP_toDJybR5SjjrnhPF3-j_PKP6-35KH35cq_PJ4JM7IOPjHWbjjM5DLMPvhaq37JD6AKh5bMln-fpQbLnCW0pkpQPoxJpOBBRbMopvaKtQteJ3vbURvD-ug3-7qaq8EK5r2SCKXJD8b3f; PSINO=1",
    	"Host:sp0.baidu.com",
    	"User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
    ];

    const CACHE_PRE = "express_data_";

    public static function query( $express_no )
    {

    	$res = F( self::CACHE_PRE.$express_no );

        if( $res )
            return $res;

    	try{

    		$res = httpRequest(self::API."&nu=".$express_no,"get",null,self::HEADER);
    		
    	}catch(\Exception $e)
    	{
    		throw $e;
    	}

    	$res = self::parseRes($res);

        if( $res && $res['is_finish'] )
        {
            F( self::CACHE_PRE.$express_no, $res );
        }

        return $res;
    }

    protected static function parseRes($res)
    {
    	if( empty($res) )
    		return FALSE;

    	$res = json_decode($res,true);

    	if( empty($res) )
    		return FALSE;

    	if( !isset($res['data']) || empty($res['data']) )
    		return FALSE;

    	if( !isset($res['data']['info']) || empty($res['data']['info']) )
    		return FALSE;

    	if( !isset($res['data']['info']['context']) || empty($res['data']['info']['context']) )
    		return FALSE;

        // echo(json_encode($res['data']));die();

    	$result= [
    		"status" => $res['data']['info']['state'],
    		"is_finish" => $res['data']['info']['state'] == 3 ? true:false,
    		"route" => $res['data']['info']['context'],
            "company" => [
                "name" => "未知方式",
                "logo" => ""
            ]
    	];

        if(isset($res['data']['source']))
        {
            $result['company'] = [
                "name" => $res['data']['source']['name'],
                "logo" => $res['data']['source']['logo']
            ];
        }

    	return $result;
    }
}